<?php
/**
 * Created by PhpStorm.
 * User: ZhangWei
 * Date: 2018/1/4
 * Time: 15:49
 */

namespace App\Http\Controllers;


use App\Events\QiniuFopEvent;
use App\Helpers\FileTool;
use App\Models\Material;
use App\Models\UserBuyOrder;
use EasyWeChat\Factory;
use Illuminate\Http\Request;

class NotifyController extends Controller
{
    /**
     * 微信支付回调 v2版本
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function xcx_wx_pay()
    {
        try {
            $config = $this->getWxAppPayConfig();
            $app = Factory::payment($config);
            $response = $app->handlePaidNotify(function ($message, $fail) {
                if ($message['result_code'] === 'SUCCESS') {
                    list($state, $msg) = UserBuyOrder::paySuccess($message['out_trade_no'], $message['transaction_id']);
                    if ($state) {
                        return true;
                    } else {
                        $fail($msg);
                    }
                } else {
                    return true;
                }
            });
            return $response;
        } catch (\Exception $exception) {
            return response()->json("error", 400);
        }

    }


    /**七牛媒体处理回调
     * @param Request $request
     * @return string
     */
    public function qiniu(Request $request)
    {
        $code = $request->json('code');
        $id = $request->json('id');
        //logger('qiniu', $request->json()->all());
        if ($code == 0) {
            $key = $request->json('items')[0]['key'];
            if (str_is('share_card*', $key)) {
                event(new QiniuFopEvent($id, [
                    'state' => true,
                    'url' => FileTool::thumb($key),
                ]));
            } else {
                Material::fopOk($id, $key);
            }
        } else {
            Material::fopFail($id);
        }


        return 'SUCCESS';
    }


}